package pl.sind.http.basic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import pl.sind.http.BaseHttpRequestResponse;
import pl.sind.http.HttpHeader;
import pl.sind.http.HttpRequest;
import pl.sind.http.HttpRequestException;

public class UrlHttpRequest extends BaseHttpRequestResponse<HttpURLConnection> implements HttpRequest<HttpURLConnection> {

	private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	
	/**
	 * Constructor setting underlying connection.<br/>
	 * You'd better not give null here ;)
	 * 
	 * @param connection
	 *            to be used by wrapper.
	 */
	public UrlHttpRequest(HttpURLConnection connection) {
		super();
		wrap(connection);
	}

	/* (non-Javadoc)
	 * @see pl.lwozniak.http.RequestWrapper#getHeader(java.lang.String)
	 */
	public String getHeader(String name) {
		return connection.getRequestProperty(name);
	}

	/* (non-Javadoc)
	 * @see pl.lwozniak.http.RequestWrapper#getOutputStream()
	 */
	public OutputStream getOutputStream() throws HttpRequestException {
		return outputStream;
	}

	public void setRequestHeader(String name, String value) {
		connection.setRequestProperty(name, value);
		
	}

	public void addRequestHeaders(String name, String value) {
		connection.addRequestProperty(name, value);
		
	}

	public void addRequestHeaders(HttpHeader[] authHeaders) {
		for (HttpHeader httpHeader : authHeaders) {
			if(httpHeader.isSingle()){
				connection.setRequestProperty(httpHeader.getName(), httpHeader.getValue());
			}else{
				connection.addRequestProperty(httpHeader.getName(), httpHeader.getValue());
			}
		}
		
	}

	public InputStream getInputStream() {
		return new ByteArrayInputStream(outputStream.toByteArray());
	}
}
